package com.app.scale.home;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.AMapLocationQualityReport;
import com.app.scale.R;
import com.app.scale.bean.BaseInfoUpdateCache;
import com.app.scale.bean.LoginBean;
import com.app.scale.dialog.UpdateBaseInfoDialog;
import com.app.scale.goods.GoodsListActivity;
import com.app.scale.greendao.GreenDaoUtils;
import com.app.scale.record.RecordListActivity;
import com.app.scale.scale.ScaleActivity;
import com.app.scale.set.AboutUsActivity;
import com.app.scale.set.SettingListActivity;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;

import butterknife.BindView;
import butterknife.OnClick;
import my.ActivityTool;
import my.DialogUtils;
import my.SystemParamsUtils;

/**
 * 首页
 */
public class HomeIndexActivity extends HomeBaseActivity {


    @BindView(R.id.text_compay_name)
    TextView text_compay_name;
    @BindView(R.id.text_scale_id)
    TextView text_scale_id;

    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;

    @Override
    public void initViews() {
        super.initViews();
        setContentView(R.layout.home_index_activity);
        //初始化定位
//        initLocation();
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        setTitleBg(R.color.transparent);
//        QMUIStatusBarHelper.translucent(mContext);
        QMUIStatusBarHelper.setStatusBarDarkMode(mContext);

//        setTitle("茶青秤");
//        ((TextView) findViewById(R.id.base_title_text)).setTextColor(getResources().getColor(R.color.white));
        text_compay_name.setText(LoginBean.getInstance().getAname());
        text_compay_name.setVisibility(View.VISIBLE);
        text_scale_id.setVisibility(View.VISIBLE);
        text_scale_id.setText(SystemParamsUtils.getAndroidID(mContext));
        checkCacheAndDownload();
    }


    void checkCacheAndDownload() {
        GreenDaoUtils.clearAll();
        BaseInfoUpdateCache beanNew  = new BaseInfoUpdateCache();
        UpdateBaseInfoDialog.toBaseInfoUpdateDialog(mContext, beanNew);
//        MySharedPreferences msp = new MySharedPreferences(mContext);
//        if (msp.isFirst(mContext)) {
//            LogUtil.i("第一次打开  或者 通讯录缓存不存在--直接更新->");
//            msp.setFirstDone(mContext);
//        } else {
//            msp.setFirstDone(mContext);
//        }
    }

    @OnClick({R.id.view_exit,R.id.view_scale,R.id.view_set,R.id.view_about,R.id.view_goods,R.id.view_record,R.id.view_tea})
    public void btnClick(View v){
        switch (v.getId()){
            case R.id.view_exit:
                System.exit(0);
                break;
            case R.id.view_set:
                ActivityTool.skipActivity(mContext, SettingListActivity.class);
                break;
            case R.id.view_scale:
                ActivityTool.skipActivity(mContext, ScaleActivity.class);
                break;
            case R.id.view_about:
                ActivityTool.skipActivity(mContext, AboutUsActivity.class);
                break;
            case R.id.view_goods:
                ActivityTool.skipActivity(mContext, GoodsListActivity.class);
                break;
            case R.id.view_record:
                ActivityTool.skipActivity(mContext, RecordListActivity.class);
                break;
            case R.id.view_tea:
//                startLocation();
                break;
            default:
//                showToast("开发中......");
//               ActivityTool.skipActivity(mContext, VideoIndexActivity.class);
//
                break;
        }
    }



    /**
     * 初始化定位
     */
    private void initLocation(){
        //初始化client
        try {
            locationClient = new AMapLocationClient(this.getApplicationContext());
            locationOption = getDefaultOption();
            //设置定位参数
            locationClient.setLocationOption(locationOption);
            // 设置定位监听
            locationClient.setLocationListener(locationListener);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 默认的定位参数
     * @since 2.8.0
     * @author hongming.wang
     *
     */
    private AMapLocationClientOption getDefaultOption(){
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        mOption.setGpsFirst(false);//可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        mOption.setHttpTimeOut(30000);//可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
//        mOption.setInterval(2000);//可选，设置定位间隔。默认为2秒
        mOption.setInterval(1000*10);
        mOption.setNeedAddress(true);//可选，设置是否返回逆地理地址信息。默认是true
        mOption.setOnceLocation(true);//可选，设置是否单次定位。默认是false
        mOption.setOnceLocationLatest(false);//可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
        mOption.setSensorEnable(false);//可选，设置是否使用传感器。默认是false
        mOption.setWifiScan(true); //可选，设置是否开启wifi扫描。默认为true，如果设置为false会同时停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        mOption.setLocationCacheEnable(true); //可选，设置是否使用缓存定位，默认为true
        mOption.setGeoLanguage(AMapLocationClientOption.GeoLanguage.DEFAULT);//可选，设置逆地理信息的语言，默认值为默认语言（根据所在地区选择语言）
        return mOption;
    }

    /**
     * 定位监听
     */
    AMapLocationListener locationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation location) {
            if (null != location) {

                StringBuffer sb = new StringBuffer();
                //errCode等于0代表定位成功，其他的为定位失败，具体的可以参照官网定位错误码说明
                if(location.getErrorCode() == 0){
                    sb.append("定位成功" + "\n");
                    sb.append("定位类型: " + location.getLocationType() + "\n");
                    sb.append("经    度    : " + location.getLongitude() + "\n");
                    sb.append("纬    度    : " + location.getLatitude() + "\n");
                    sb.append("国    家    : " + location.getCountry() + "\n");
                    sb.append("省            : " + location.getProvince() + "\n");
                    sb.append("市            : " + location.getCity() + "\n");
                    sb.append("地    址    : " + location.getAddress() + "\n");
                } else {
                    //定位失败
                    sb.append("定位失败" + "\n");
                    sb.append("错误码:" + location.getErrorCode() + "\n");
                    sb.append("错误信息:" + location.getErrorInfo() + "\n");
                    sb.append("错误描述:" + location.getLocationDetail() + "\n");
                }
                sb.append("***定位质量报告***").append("\n");
                sb.append("* WIFI开关：").append(location.getLocationQualityReport().isWifiAble() ? "开启":"关闭").append("\n");
                sb.append("* GPS状态：").append(getGPSStatusString(location.getLocationQualityReport().getGPSStatus())).append("\n");
                sb.append("* GPS星数：").append(location.getLocationQualityReport().getGPSSatellites()).append("\n");
                sb.append("* 网络类型：" + location.getLocationQualityReport().getNetworkType()).append("\n");
                sb.append("* 网络耗时：" + location.getLocationQualityReport().getNetUseTime()).append("\n");
                sb.append("****************").append("\n");

                //解析定位结果，
                String result = sb.toString();
                DialogUtils.showWarningDialog(mContext,result);
            } else {
                showToast("定位失败，loc is null");
            }
        }
    };


    /**
     * 获取GPS状态的字符串
     * @param statusCode GPS状态码
     * @return
     */
    private String getGPSStatusString(int statusCode){
        String str = "";
        switch (statusCode){
            case AMapLocationQualityReport.GPS_STATUS_OK:
                str = "GPS状态正常";
                break;
            case AMapLocationQualityReport.GPS_STATUS_NOGPSPROVIDER:
                str = "手机中没有GPS Provider，无法进行GPS定位";
                break;
            case AMapLocationQualityReport.GPS_STATUS_OFF:
                str = "GPS关闭，建议开启GPS，提高定位质量";
                break;
            case AMapLocationQualityReport.GPS_STATUS_MODE_SAVING:
                str = "选择的定位模式中不包含GPS定位，建议选择包含GPS定位的模式，提高定位质量";
                break;
            case AMapLocationQualityReport.GPS_STATUS_NOGPSPERMISSION:
                str = "没有GPS定位权限，建议开启gps定位权限";
                break;
        }
        return str;
    }


    /**
     * 开始定位
     *
     * @since 2.8.0
     * @author hongming.wang
     *
     */
    private void startLocation(){
        try {
            // 设置定位参数
            locationClient.setLocationOption(locationOption);
            // 启动定位
            locationClient.startLocation();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopLocation();
    }

    /**
     * 停止定位
     *
     * @since 2.8.0
     * @author hongming.wang
     *
     */
    private void stopLocation(){
        try {
            // 停止定位
            locationClient.stopLocation();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
